package com.mofeng.myshop.service.impl;

import com.mofeng.myshop.domain.dto.CarmineDto;
import com.mofeng.myshop.domain.dto.search.CarmineQo;
import com.mofeng.myshop.domain.po.Carmine;
import com.mofeng.myshop.domain.po.UserBase;
import com.mofeng.myshop.domain.po.UserInfo;
import com.mofeng.myshop.domain.vo.CarmineVo;
import com.mofeng.myshop.domain.vo.base.PageMp;
import com.mofeng.myshop.domain.vo.user.UserVo;
import com.mofeng.myshop.mapper.CarmineMapper;
import com.mofeng.myshop.mapper.UserBaseMapper;
import com.mofeng.myshop.mapper.UserInfoMapper;
import com.mofeng.myshop.service.CarmineService;
import com.mofeng.myshop.until.Constants;
import com.mofeng.myshop.until.LoginUserThreadLocalUtil;
import com.mofeng.myshop.until.MyUtil;
import com.mofeng.myshop.until.R;
import com.mofeng.myshop.until.component.CookieUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 卡密 服务实现类
 *
 * @author 作者
 * @since 2024-11-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class CarmineServiceImpl implements CarmineService {

    private final CarmineMapper carmineMapper;

    private final UserBaseMapper userBaseMapper;

    private final UserInfoMapper userInfoMapper;
    private final CookieUtils cookieUtils;

    /**
     * 创建 卡密
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R createCarmine(CarmineDto carmineDto) {
        String money = carmineDto.getMoney();
        if (MyUtil.StringUtil.isEmpty(money)) {
            throw new RuntimeException("金额不能为空");
        }
        Double moneyDouble = MyUtil.NumberUtil.asDouble(money);
        if (moneyDouble < 0) {
            throw new RuntimeException("开卡金额不能小于0");
        }
        Integer count = carmineDto.getCount();
        if (MyUtil.StringUtil.isEmpty(count) || count < 1) {
            throw new RuntimeException("开卡数量最少为1");
        }
        String name = "金额" + money + "充值卡";
        for (Integer i = 0; i < count; i++) {
            Carmine carmine = new Carmine();
            carmine.setUserId(null);
            carmine.setMoneyDouble(moneyDouble);
            carmine.setName(name);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            uuid = MyUtil.DoubleUtil.doubleFormatToStr(moneyDouble, 2) + "-" + uuid;
            carmine.setUuid(uuid);
            carmine.setUsed(Constants.Carmine.DEFAULT_STATE);
            carmineMapper.insert(carmine);
        }
        return R.SUCCESS(name + ",数量" + count + "张，开卡成功");
    }

    /**
     * 单个删除 卡密
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteCarmine(Long id) {
        carmineMapper.deleteById(id);
        return R.SUCCESS("删除成功");
    }

    /**
     * 批量真实删除 卡密
     *
     * @param ids
     */
    @Override
    public R deleteCarmineList(List<Long> ids) {
        for (Long id : ids) {
            carmineMapper.deleteById(id);
        }
        return R.SUCCESS("删除成功");
    }


    @Override
    public R findPage(CarmineQo carmineQo) {
        Page<Carmine> carminePage = carmineQo.getPageMp();
        String money = carmineQo.getMoney();
        Long userId = carmineQo.getUserId();
        Integer used = carmineQo.getUsed();
        Date startTime = carmineQo.getStartTime();
        Date endTime = carmineQo.getEndTime();
        if (!MyUtil.StringUtil.isEmpty(money)) {
            money = String.format("%.3f", MyUtil.NumberUtil.asDouble(money));
        }
        Page<Carmine> carminePageFromDb = carmineMapper.findPage(startTime, endTime, money, userId, used, carminePage);
        return R.SUCCESS("获取成功").setData(new PageMp<>(carminePageFromDb, CarmineVo::new));
    }

    /**
     * 使用卡密
     *
     * @param code 卡密
     * @return 0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R useCarmine(String code) {
        UserVo userVo = LoginUserThreadLocalUtil.get();
        if (userVo == null) {
            throw new RuntimeException("请先登录");
        }
        UserBase userBase = userBaseMapper.findAllInfoById(MyUtil.NumberUtil.asLong(userVo.getId()));
        if (userBase == null) {
            throw new RuntimeException("找不到登录用户");
        }
        UserInfo info = userBase.getInfo();

        Set<Carmine> carmineSet = carmineMapper.findByUuid(code);
        if (carmineSet == null || carmineSet.isEmpty()) {
            throw new RuntimeException("卡密错误");
        }
        List<Carmine> carmineList = new ArrayList<>(carmineSet);
        Carmine carmine = carmineList.get(0);
        Integer used = carmine.getUsed();
        if (Constants.Carmine.USED_STATE.equals(used)) {
            throw new RuntimeException("卡密已经使用");
        }
        String money = carmine.getMoney();
        String moneyUser = info.getMoney();
        info.setMoneyDouble(MyUtil.NumberUtil.asDouble(money) + MyUtil.NumberUtil.asDouble(moneyUser));

        carmine.setUsed(Constants.Carmine.USED_STATE);
        carmine.setUserId(userBase.getId());
        userInfoMapper.updateById(info);
        carmineMapper.updateById(carmine);
        return R.SUCCESS("充值成功");
    }
}
